package com.cl.gateway.config;

//import com.cl.oauth.core.common.model.vo.ResourceAuthority;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 权限相关的配置和认证参数，放在nacos中，用于网关对请求的权限鉴定
 */
@Configuration
@ConfigurationProperties(prefix = "auth.authenticate")
public class AuthorizationProperties {

    private final AntPathMatcher antPathMatcher;

    public AuthorizationProperties() {
        this.antPathMatcher = new AntPathMatcher();
    }

    /**
     * 需要权限认证的资源集合
     */
    private Map<String, List<ResourceAuthority>> resources;

    public Map<String, List<ResourceAuthority>> getResources() {
        return resources;
    }

    public void setResources(Map<String, List<ResourceAuthority>> resources) {
        this.resources = resources;
    }

    /**
     * 获取指定请求需要的权限
     * @param requestPath 当前需要获取权限的请求
     * @param method 当前方法
     * @return 权限字符串
     */
    public Set<String> getRequestNeedPermission(String requestPath, String method) {
        List<ResourceAuthority> list = this.resources.get(method.toUpperCase());

        if(null == list || list.size() == 0) {
            return null;
        }

        // 获取找到的权限列表
        return list.stream().filter(v -> antPathMatcher.match(v.getPath(), requestPath))
                .map(ResourceAuthority::getAuthority).collect(Collectors.toSet());
    }
}
